package com.ruoyi.web.controller.teaching;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.teaching.domain.*;
import com.ruoyi.teaching.service.*;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学生记上课Controller
 *
 * @author ruoyi
 * @date 2022-10-20
 */
@Controller
@RequestMapping("/teaching/record")
public class TeachingStudentRecordController extends BaseController {
    private String prefix = "teaching/record";

    @Autowired
    private ITeachingStudentRecordService teachingStudentRecordService;

    @Autowired
    private ITeachingClassesScheduleService teachingClassesScheduleService;

    @Autowired
    private ITeachingClassesService teachingClassesService;

    @Autowired
    private ITeachingStudentApplyService teachingStudentApplyService;

    @Autowired
    private ITeachingClassesRecordService teachingClassesRecordService;

    @Autowired
    private ITeachingCourseService teachingCourseService;

    @Autowired
    private ITeachingClassesStudentsService teachingClassesStudentsService;

    @Autowired
    private ISysUserService userService;

    //    @RequiresPermissions("teaching:record:view")
    @GetMapping()
    public String record() {
        return prefix + "/homePage";
    }

    /**
     * 查询学生记上课列表
     */
//    @RequiresPermissions("teaching:record:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TeachingStudentRecord teachingStudentRecord) {
        startPage();
        teachingStudentRecord.setSchoolId(getSysUser().getSchoolId());
        List<TeachingStudentRecord> list = teachingStudentRecordService.selectTeachingStudentRecordList(teachingStudentRecord);
        for (TeachingStudentRecord record : list) {
            Long claRecordId = record.getClaRecordId();
            Long applyId = record.getApplyId();
            Long classId = record.getClassId();
            record.setTeachingClasses(teachingClassesService.selectTeachingClassesByClassId(classId));
            record.setTeachingStudentApply(teachingStudentApplyService.selectTeachingStudentApplyByApplyId(applyId));
            record.setTeachingClassesRecord(teachingClassesRecordService.selectTeachingClassesRecordByClaRecordId(claRecordId));
        }
        return getDataTable(list);
    }

    /**
     * 导出学生记上课列表
     */
//    @RequiresPermissions("teaching:record:export")
    @Log(title = "学生记上课", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TeachingStudentRecord teachingStudentRecord) {
        List<TeachingStudentRecord> list = teachingStudentRecordService.selectTeachingStudentRecordList(teachingStudentRecord);
        ExcelUtil<TeachingStudentRecord> util = new ExcelUtil<TeachingStudentRecord>(TeachingStudentRecord.class);
        return util.exportExcel(list, "学生记上课数据");
    }

    /**
     * 新增学生记上课
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存学生记上课
     */
//    @RequiresPermissions("teaching:record:add")
    @Log(title = "学生记上课", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(TeachingStudentRecord teachingStudentRecord) {
        teachingStudentRecord.setCreateBy(getLoginName());
        teachingStudentRecord.setCreateId(getUserId());
        teachingStudentRecord.setCreateTime(new Date());
        return toAjax(teachingStudentRecordService.insertTeachingStudentRecord(teachingStudentRecord));
    }


    @PostMapping("/addList")
    @ResponseBody
    public AjaxResult addList(@RequestBody List<TeachingStudentRecord> teachingStudentRecords) {
        for (TeachingStudentRecord teachingStudentRecord : teachingStudentRecords) {
            teachingStudentRecord.setCreateBy(getLoginName());
            teachingStudentRecord.setCreateId(getUserId());
            teachingStudentRecord.setCreateTime(new Date());
            //扣除每个学生的课时
            Long applyId = teachingStudentRecord.getApplyId();
            TeachingStudentApply teachingStudentApply = teachingStudentApplyService.selectTeachingStudentApplyByApplyId(applyId);
            Integer lessonRemain1 = teachingStudentApply.getLessonRemain();
            Integer lessonConsume1 = teachingStudentApply.getLessonConsume();
            Integer lessonConsume2 = Convert.toInt(teachingStudentRecord.getLessonConsume());
            lessonRemain1 = lessonRemain1 - lessonConsume2;
            lessonConsume1 = lessonConsume1 + lessonConsume2;
            teachingStudentApply.setLessonRemain(lessonRemain1);
            teachingStudentApply.setLessonConsume(lessonConsume1);
            //添加该班级里学生的请假次数
            Long classStudentId = teachingStudentRecord.getClassStudentId();
            TeachingClassesStudents teachingClassesStudents = teachingClassesStudentsService.selectTeachingClassesStudentsByClassStudentId(classStudentId);
            Long leaveCount1 = teachingStudentRecord.getLeaveCount();
            teachingClassesStudents.setLeaveCount(leaveCount1);
            //添加该班级里学生的课时消耗
            Long lessonConsume3 = teachingClassesStudents.getLessonConsume();
            lessonConsume3 = lessonConsume3 + lessonConsume2;
            teachingClassesStudents.setLessonConsume(lessonConsume3);
            teachingClassesStudentsService.updateTeachingClassesStudents(teachingClassesStudents);
            teachingStudentApplyService.updateTeachingStudentApply(teachingStudentApply);
            teachingStudentRecordService.insertTeachingStudentRecord(teachingStudentRecord);
        }
        return success();
    }

    /**
     * 修改学生记上课
     */
//    @RequiresPermissions("teaching:record:edit")
    @GetMapping("/edit/{recordId}")
    public String edit(@PathVariable("recordId") Long recordId, ModelMap mmap) {
        TeachingStudentRecord teachingStudentRecord = teachingStudentRecordService.selectTeachingStudentRecordByRecordId(recordId);
        Long classId = teachingStudentRecord.getClassId();
        TeachingClasses classes = teachingClassesService.selectTeachingClassesByClassId(classId);
        mmap.put("teachingClasses", classes);
        mmap.put("teachingStudentRecord", teachingStudentRecord);
        return prefix + "/edit";
    }

    /**
     * 修改保存学生记上课
     */
//    @RequiresPermissions("teaching:record:edit")
    @Log(title = "学生记上课", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(TeachingStudentRecord teachingStudentRecord) {
        return toAjax(teachingStudentRecordService.updateTeachingStudentRecord(teachingStudentRecord));
    }

    @PostMapping("/editRecord")
    @ResponseBody
    public AjaxResult updateRecord(TeachingStudentRecord teachingStudentRecord) {
        //修改上课记录的同时修改课时
        Long applyId = teachingStudentRecord.getApplyId();
        TeachingStudentApply teachingStudentApply = teachingStudentApplyService.selectTeachingStudentApplyByApplyId(applyId);
        Integer lessonRemain1 = teachingStudentApply.getLessonRemain();
        Integer lessonConsume1 = teachingStudentApply.getLessonConsume();
        Integer lessonConsume2 = Convert.toInt(teachingStudentRecord.getLessonConsume());
        lessonRemain1 = lessonRemain1 + lessonConsume1 - lessonConsume2;
        teachingStudentApply.setLessonRemain(lessonRemain1);
        teachingStudentApply.setLessonConsume(lessonConsume2);
        Long claRecordId = teachingStudentRecord.getClaRecordId();
        //修改班级的学生修改的课时
        Long classStudentId = teachingStudentRecord.getClassStudentId();
        TeachingClassesStudents teachingClassesStudents = teachingClassesStudentsService.selectTeachingClassesStudentsByClassStudentId(classStudentId);
        Long lessonConsume3 = teachingClassesStudents.getLessonConsume();
        lessonConsume3 = lessonConsume3 - lessonConsume1 + lessonConsume2;
        teachingClassesStudents.setLessonConsume(lessonConsume3);
        //修改班级里的学生请假次数
        Long leaveCount1 = teachingStudentRecord.getLeaveCount();
        teachingClassesStudents.setLeaveCount(leaveCount1);
        teachingClassesStudentsService.updateTeachingClassesStudents(teachingClassesStudents);
        teachingStudentApplyService.updateTeachingStudentApply(teachingStudentApply);
        teachingStudentRecordService.updateTeachingStudentRecord(teachingStudentRecord);
        updateClaRecord(claRecordId);
        return success();
    }


    private void updateClaRecord(Long claRecordId) {
        TeachingClassesRecord classesRecord = teachingClassesRecordService.selectTeachingClassesRecordByClaRecordId(claRecordId);
        if (StringUtils.isNotNull(classesRecord)) {
            TeachingStudentRecord param = new TeachingStudentRecord();
            param.setClaRecordId(claRecordId);
            List<TeachingStudentRecord> totalRecord = teachingStudentRecordService.selectTeachingStudentRecordList(param);
            //到课人数
            int attendanceCount = totalRecord.stream().filter(a -> a.getAttendStatus().equals("0")).collect(Collectors.toList()).size();
            //请假人数
            int leaveCount = totalRecord.stream().filter(a -> a.getAttendStatus().equals("1")).collect(Collectors.toList()).size();
            //旷课人数
            int truantCount = totalRecord.stream().filter(a -> a.getAttendStatus().equals("2")).collect(Collectors.toList()).size();
            //消耗课时统计
            Long studentHour = totalRecord.stream().mapToLong(a->a.getLessonConsume()).sum();
            classesRecord.setAttendance(Convert.toLong(attendanceCount));
            classesRecord.setLeaveCount(Convert.toLong(leaveCount));
            classesRecord.setTruantCount(Convert.toLong(truantCount));
            classesRecord.setStudentHour(studentHour);
            teachingClassesRecordService.updateTeachingClassesRecord(classesRecord);
        }
    }

    /**
     * 删除多名学生记上课
     */
//    @RequiresPermissions("teaching:record:remove")
    @Log(title = "学生记上课", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(teachingStudentRecordService.deleteTeachingStudentRecordByRecordIds(ids));
    }

    /**
     * 删除学生记上课
     */
    @PostMapping("/removeOne/{recordId}")
    @ResponseBody
    public AjaxResult removeOne(@PathVariable("recordId") Long recordId){
        TeachingStudentRecord studentRecord = teachingStudentRecordService.selectTeachingStudentRecordByRecordId(recordId);
        Long applyId = studentRecord.getApplyId();
        Integer lessonConsume = Convert.toInt(studentRecord.getLessonConsume());
        TeachingStudentApply studentApply = teachingStudentApplyService.selectTeachingStudentApplyByApplyId(applyId);
        Integer lessonRemain = studentApply.getLessonRemain();
        Integer lessonConsume1 = studentApply.getLessonConsume();
        lessonRemain = lessonRemain + lessonConsume;
        lessonConsume1 = lessonConsume1 - lessonConsume;
        studentApply.setLessonRemain(lessonRemain);
        studentApply.setLessonConsume(lessonConsume1);
        Long claRecordId = studentRecord.getClaRecordId();
        teachingStudentApplyService.updateTeachingStudentApply(studentApply);
        teachingStudentRecordService.deleteTeachingStudentRecordByRecordId(recordId);
        updateClaRecord(claRecordId);
        return success();
    }

    /**
     * 查看班级学生消课界面
     */
    @GetMapping("/consume/{scheduleId}")
    public String consume(@PathVariable("scheduleId") Long scheduleId, ModelMap mmap) {
        TeachingClassesSchedule teachingClassesSchedule = teachingClassesScheduleService.selectTeachingClassesScheduleByScheduleId(scheduleId);
        Long classId = teachingClassesSchedule.getClassId();
        TeachingClasses teachingClasses = teachingClassesService.selectTeachingClassesByClassId(classId);
        mmap.put("teachingClasses", teachingClasses);
        mmap.put("teachingClassesSchedule", teachingClassesSchedule);
        return prefix + "/consume";
    }


    /**
     * 编辑班级学生消课界面
     */
    @GetMapping("/editModal/{scheduleId}")
    public String editModal(@PathVariable("scheduleId") Long scheduleId, ModelMap mmap) {
        TeachingClassesSchedule teachingClassesSchedule = teachingClassesScheduleService.selectTeachingClassesScheduleByScheduleId(scheduleId);
        TeachingClasses teachingClasses = teachingClassesService.selectTeachingClassesByClassId(teachingClassesSchedule.getClassId());
        mmap.put("teachingClassesSchedule", teachingClassesSchedule);
        mmap.put("teachingClasses", teachingClasses);
        return prefix + "/editModal";
    }

    /**
     * 未排课记上课
     */
    @GetMapping("/nonscheduled")
    public String nonscheduled(){
        return prefix + "/nonscheduled";
    }

    /**
     * 添加临时学员列表
     */
    @GetMapping("/temporaryStudent/{classId}")
    public String temporaryStudent(@PathVariable("classId") Long classId, ModelMap mmap){
        TeachingClasses teachingClasses = teachingClassesService.selectTeachingClassesByClassId(classId);
        mmap.put("teachingClasses",teachingClasses);
        return prefix + "/temporaryStudent";
    }

    /**
     * 未排课记上课
     */
    @GetMapping("/tmpConsume/{classId}")
    public String tmpConsume(@PathVariable("classId") Long classId, ModelMap mmap) {
        TeachingClasses teachingClasses = teachingClassesService.selectTeachingClassesByClassId(classId);
        //找出当前账号所在学校的所有老师
        SysUser param = new SysUser();
        param.setSchoolId(getSysUser().getSchoolId());
        param.setUserType("00");
        List<SysUser> teachers = userService.selectUserList(param);
        mmap.put("teachers", teachers);
        mmap.put("teachingClasses", teachingClasses);
        return prefix + "/tmpConsume";
    }
}
